import smtplib
from email.mime.text import MIMEText
from email.header import Header
from traceback import format_exc
# Local
from m_constant import f_logError, nowTime
from m_iniRead import format_file as format_info


def Traceback():
    with open(f_logError, mode='a', encoding='utf8') as f_e:
        f_e.write(f'**********{nowTime}**********\n{format_exc()}\n\n')


def send_email(info_email, title, msg):
    # 第三方 SMTP 服务
    emInfo = format_info(info_email)
    # print(emInfo)
    receiver = emInfo['receiver']           # 收件人 (List or Str)
    sender = emInfo['sender']               # 发件人
    mailHost = emInfo['mailHost']           # SMTP 服务器
    mailUser = emInfo['mailUser']           # User
    mailPasswd = emInfo['mailPasswd']       # Passwd

    message = MIMEText(msg, 'plain', 'utf-8')  # 创建消息实例 内容 格式（plain，html） 编码
    message['Subject'] = Header(title, 'utf-8')  # 消息的 主题或标题
    message['from'] = f'IPAddr<{sender}>'                        # 发件人
    message['to'] = receiver                        # 收件人

    try:
        smtpObj = smtplib.SMTP(host=mailHost)       # 建立SMTP链接的实例, (从3.7开始实例化需要指定Host)
        smtpObj.connect(mailHost, 25)               # 25 为 SMTP 端口号 - 链接到SMTP的服务器
        smtpObj.login(mailUser, mailPasswd)         # 登录用户
        smtpObj.sendmail(sender, receiver, message.as_string())  # 发送邮件-发件人-收件人- 消息对象
        print("邮件发送成功")
        return 0, receiver
    except smtplib.SMTPConnectError and smtplib.SMTPDataError:
        print("Error: 无法发送邮件")
        # remove(f_ipv4)
        Traceback()
        return -1, receiver


if __name__ == "__main__":
    send_email('函数中测试', '汉族')
